//
//  ConfirmViewController.m
//  Printer
//
//  Created by Bcc on 5/15/16.
//  Copyright © 2016 eReach. All rights reserved.
//

#import "ConfirmViewController.h"
#import "UEButton.h"
#import "UAProgressView.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MBProgressHUD+MJ.h"
#import "TestViewController.h"
//#import "UIPrintInteractionController.h"
@interface ConfirmViewController ()<UIPrintInteractionControllerDelegate>
{
    UIView *animationBgView;
    UEButton *confirm;
    NSTimer *_timer;
    NSString *_airPrinterUrlStr;
    NSString *_airPrinterName;
    long double rotate ;
}
@property (nonatomic, strong)UAProgressView *progressView;

@property (nonatomic, strong)UIPrintInteractionController *airPrinterController;
@property (nonatomic, assign) SystemSoundID horn;
@property (nonatomic, assign) BOOL paused;
@property (nonatomic, assign) CGFloat localProgress;


@property(nonatomic,strong)UIBarButtonItem *printButton;
@end

@implementation ConfirmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = Blue_Color;
//    rotate =  3 * M_PI_2;
    rotate = 0.0;
    
    
    self.selectImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.selectImageView.image = self.image;
    [self addButons];
    
    [self addProgressView];
    [self setAnimationMethod];
    
    
}


- (void)addProgressView
{
    animationBgView = [[UIView alloc] init];
    animationBgView.hidden = YES;
    animationBgView.userInteractionEnabled = NO;
    animationBgView.frame = self.view.bounds;
    animationBgView.backgroundColor = [UIColor colorWithRed:0.949 green:0.941 blue:0.953 alpha:0.900];
//    animationBgView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:animationBgView];
    
    _progressView = [[UAProgressView alloc] init];
    _progressView.frame = CGRectMake(0, 0, 326, 326);
    _progressView.center = CGPointMake(SCREEN_W/2, SCREEN_H/2);
    [animationBgView addSubview:_progressView];
    
}

- (void)addButons
{
    
    CGFloat bigBtnW = 76;
    CGFloat bigBtnMargin = 36;
    CGFloat bigBtnY = 641;
    
    
    UEButton *rotateBtn = [[UEButton alloc] initWithFrame:CGRectMake(SCREEN_W/2 - bigBtnW*3/2 - bigBtnMargin,bigBtnY, bigBtnW, bigBtnW)];
    [rotateBtn setImage:[UIImage imageNamed:@"rotate_icon"] forState:UIControlStateNormal];
    [rotateBtn addTarget:self action:@selector(rotateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rotateBtn];
    
    
    
    confirm = [[UEButton alloc] initWithFrame:CGRectMake(SCREEN_W/2 - bigBtnW/2,bigBtnY, bigBtnW, bigBtnW)];
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirm];
    
    UEButton *cancel = [[UEButton alloc] initWithFrame:CGRectMake(SCREEN_W/2 + bigBtnW/2 + bigBtnMargin, bigBtnY, bigBtnW, bigBtnW)];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancel];
    

}



-(UIImage *)getImageFromView:(UIView *)view{
//    UIGraphicsBeginImageContext(view.bounds.size);
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 1.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



- (void)rotateBtnClick:(UIButton *)sender
{
    self.selectImageView.image = [self rotateImage:self.image];
}


- (void)cancel:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)confirm:(UIButton *)sender
{
//    if (IOS_8) {
//        
//    }else{
//        [self airPrint];
//    }
    
  
//    UIImage *printImg = [self getImageFromView:self.printView];
//    
//    TestViewController *tc = [self.storyboard instantiateViewControllerWithIdentifier:@"TestViewController"];
//    tc.image = printImg;
//    [self presentViewController:tc animated:YES completion:^{
//        
//    }];
    [self showAnimation];
    [self airPrint];
//    [self printWithOutUI];
    
}


- (void)showAnimation
{
    animationBgView.hidden = NO;
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.6 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];
    [_timer fire];
}

- (void)printWithOutUI
{
    _airPrinterUrlStr = @"";
    _airPrinterUrlStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"url"];
//    _airPrinterName = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    if (_airPrinterUrlStr.length != 0) {
        [self showAnimation];
        UIImage *printImg = [self getImageFromView:self.printView];
        [self startAirPrintWithImage:printImg];
        return;
    }
    
    UIPrinterPickerController *pickerController =[UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:nil];
    
    CGRect rect;
    rect = CGRectMake(SCREEN_W/2,145,0,0);
    [pickerController presentFromRect:rect inView:self.view animated:YES completionHandler:^(UIPrinterPickerController *controller, BOOL userDidSelect, NSError *err){
        if (userDidSelect)
        {
            // save the urlString and Printer name, do your UI interactions
            
            _airPrinterUrlStr = controller.selectedPrinter.URL.absoluteString;
            _airPrinterName = controller.selectedPrinter.displayName;
            NSLog(@"Selected printer:%@   \nURL:%@", controller.selectedPrinter.displayName,_airPrinterUrlStr);
            [[NSUserDefaults standardUserDefaults] setObject:_airPrinterUrlStr forKey:@"url"];
            [[NSUserDefaults standardUserDefaults] setObject:_airPrinterName forKey:@"name"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[UIPrinter printerWithURL:[NSURL URLWithString:_airPrinterUrlStr]] contactPrinter:^(BOOL available)
             {
                 if (available)
                 {
                     NSLog(@"AIRPRINTER AVAILABLE");
                     [self showAnimation];
                     UIImage *printImg = [self getImageFromView:self.printView];
                     [self startAirPrintWithImage:printImg];
                 }
                 else
                 {
                     NSLog(@"AIRPRINTER NOT AVAILABLE");
                     [MBProgressHUD showError:@"没找到打印机"];
                 }
             }];
        }
    }];
    
}


- (void)startAirPrintWithImage:(UIImage *)image
{
    
    
    NSLog(@"照片已打印");
//    
//    return;
    /************************* Set Print Info ************************/
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputPhoto;
    printInfo.orientation = UIPrintInfoOrientationLandscape;
    printInfo.jobName = @"CoolVisitAirPrint";
    
    self.airPrinterController.printInfo = printInfo;
    self.airPrinterController.printingItem = image;
    self.airPrinterController.delegate = self;
    
    /************************* Print ************************/
    /* Set up a completion handler block.  If the print job has an error before spooling, this is where it's handled. */
    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if(completed && error)
            NSLog(@"Printing failed due to error in domain %@ with error code %lu. Localized description: %@, and failure reason: %@", error.domain, (long)error.code, error.localizedDescription, error.localizedFailureReason);
    };
    
    UIPrinter *airPrinter = [UIPrinter printerWithURL:[NSURL URLWithString:_airPrinterUrlStr]];
    [self.airPrinterController printToPrinter:airPrinter completionHandler:completionHandler];
}



- (void)airPrint
{
    self.photoFrame.image = [UIImage imageNamed:@"photo_frame_print"];
    UIImage *printImg = [self getImageFromView:self.printView];
    self.photoFrame.image = [UIImage imageNamed:@"photo_frame_print"];
    
    NSData *imageData = nil;
    
    if (UIImagePNGRepresentation(printImg) == nil) {
        
        imageData = UIImageJPEGRepresentation(printImg, 1);
        
    } else {
        imageData = UIImagePNGRepresentation(printImg);
    }
    UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];    if(!controller)
    {
        NSLog(@"Couldn't get shared UIPrintInteractionController!");
        return;
    }
    controller.delegate = self;
    
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = @"ACBA";
    printInfo.duplex = UIPrintInfoDuplexNone;
    controller.printInfo = printInfo;
    controller.showsPageRange = YES;
    controller.printingItem = imageData;
    
    
    void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        
    };
    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
    {
        //iPad
        [controller presentFromRect:CGRectMake(SCREEN_W/2,145,0,0) inView:self.view animated:YES completionHandler:completionHandler];
    }
    else
    {
        [controller presentAnimated:YES completionHandler:completionHandler];
    }
    
    
    
}


- (void)printInteractionControllerWillStartJob:(UIPrintInteractionController *)printInteractionController
{
    NSLog(@"printInteractionControllerWillStartJob");
    [self showAnimation];
    
}
- (void)printInteractionControllerDidFinishJob:(UIPrintInteractionController *)printInteractionController
{
    NSLog(@"printInteractionControllerDidFinishJob");
}

- (void)setAnimationMethod
{
    
    self.progressView.tintColor = Blue_Color;
    self.progressView.borderWidth = 0.0;
//    DCDDDD
    self.progressView.lineWidth = 13.0;
    self.progressView.fillOnTouch = YES;
    
    UIView *hintView = [[UIView alloc] init];
    hintView.frame = CGRectMake(0, 0, 300.0, 118.0);
    hintView.backgroundColor = [UIColor clearColor];
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300.0, 97.0)];
    textLabel.font = [UIFont systemFontOfSize:64];
    textLabel.tag = 888;
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.textColor = Blue_Color;
    textLabel.backgroundColor = [UIColor clearColor];
    [hintView addSubview:textLabel];
    
    UILabel *subTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, 300.0, 21.0)];
    subTextLabel.font = [UIFont systemFontOfSize:18];
    subTextLabel.text = @"请稍等，正在打印中…";
    subTextLabel.textAlignment = NSTextAlignmentCenter;
    subTextLabel.textColor = [UIColor colorWithRed:0.137 green:0.098 blue:0.086 alpha:1.000];
    subTextLabel.backgroundColor = [UIColor clearColor];
    [hintView addSubview:subTextLabel];
    
    
    
    self.progressView.centralView = hintView;
    
    self.progressView.fillChangedBlock = ^(UAProgressView *progressView, BOOL filled, BOOL animated){
//        UIColor *color = (filled ? [UIColor whiteColor] : progressView.tintColor);
//        if (animated) {
//            [UIView animateWithDuration:0.3 animations:^{
//                [(UILabel *)progressView.centralView setTextColor:color];
//            }];
//        } else {
//            [(UILabel *)progressView.centralView setTextColor:color];
//        }
    };
    
    self.progressView.progressChangedBlock = ^(UAProgressView *progressView, CGFloat progress){
        UILabel *ll =  (UILabel *)[progressView.centralView viewWithTag:888];
        [ll setText:[NSString stringWithFormat:@"%2.0f%%", progress * 100]];
    };
    
//    NSString *path  = [[NSBundle mainBundle] pathForResource:@"horn" ofType:@"caf"];
//    NSURL *pathURL = [NSURL fileURLWithPath : path];
//    AudioServicesCreateSystemSoundID((__bridge CFURLRef) pathURL, &_horn);
//    
    self.progressView.didSelectBlock = ^(UAProgressView *progressView){
//        AudioServicesPlaySystemSound(_horn);
//        _paused = !_paused;
    };
    
    self.progressView.progress = 0;
    
}

- (void)updateProgress:(NSTimer *)timer {

    _localProgress = ((int)((_localProgress * 100.0f) + 1.01) % 100) / 100.0f;
    NSLog(@"%f",_localProgress);
    [self.progressView setProgress:_localProgress];
    if (self.progressView.progress >= 0.99) {
        [self.progressView setProgress:1];
        [_timer invalidate];
        animationBgView.hidden = YES;
        [self cancel:nil];
    }
}




- (UIImage *)rotateImage:(UIImage *)image
{
    
    rotate = M_PI_2 + rotate;
    
    int orientation = (int)(rotate/M_PI_2)%4;
    NSLog(@"---rotate:%Lf--angle:%f---%d",rotate,M_PI_2,orientation);
    switch (orientation) {
        case 3:
            return [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationLeft];
            break;
        case 1:
            return [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationRight];
            break;
        case 2:
            return [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationDown];
            break;
        default:
            return [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp];
            break;
    }
    
}


- (UIImage *)rotateImage111111:(UIImage *)image
{
    
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    rotate = M_PI_2 + rotate;
    
    int orientation = (int)(rotate/M_PI_2)%4;
    NSLog(@"---rotate:%Lf--angle:%f---%d",rotate,M_PI_2,orientation);
    switch (orientation) {
        case 3:
//            rotate = M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = -rect.size.height;
            translateY = 0;
            
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case 1:
//            rotate = 3 * M_PI_2;
            rect = CGRectMake(0, 0, image.size.height, image.size.width);
            translateX = 0;
            translateY = -rect.size.width;
            scaleY = rect.size.width/rect.size.height;
            scaleX = rect.size.height/rect.size.width;
            break;
        case 2:
//            rotate = M_PI;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = -rect.size.width;
            translateY = -rect.size.height;
            break;
        default:
//            rotate = 0.0;
            rect = CGRectMake(0, 0, image.size.width, image.size.height);
            translateX = 0;
            translateY = 0;
            break;
    }
    
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
    
    
//case 3:
//    //            rotate = M_PI_2;
//    rect = CGRectMake(0, 0, image.size.height, image.size.width);
//    translateX = 0;
//    translateY = -rect.size.width;
//    scaleY = rect.size.width/rect.size.height;
//    scaleX = rect.size.height/rect.size.width;
//    break;
//case 1:
//    //            rotate = 3 * M_PI_2;
//    rect = CGRectMake(0, 0, image.size.height, image.size.width);
//    translateX = -rect.size.height;
//    translateY = 0;
//    scaleY = rect.size.width/rect.size.height;
//    scaleX = rect.size.height/rect.size.width;
//    break;
//case 2:
//    //            rotate = M_PI;
//    rect = CGRectMake(0, 0, image.size.width, image.size.height);
//    translateX = -rect.size.width;
//    translateY = -rect.size.height;
//    break;
//default:
//    //            rotate = 0.0;
//    rect = CGRectMake(0, 0, image.size.width, image.size.height);
//    translateX = 0;
//    translateY = 0;
//    break;
}

@end
